package com.yunyao.web.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.yunyao.common.dto.ReconciliationDto;
import com.yunyao.common.dto.ReconciliationOrderDto;
import com.yunyao.common.dto.excel.ContractExcelDto;
import com.yunyao.common.dto.excel.ReconciliationExcelDto;
import com.yunyao.common.dto.excel.SupplyExcelDto;
import com.yunyao.common.dto.project.HistoryQtDto;
import com.yunyao.common.web.util.PageResult;
import com.yunyao.common.web.util.YResult;
import com.yunyao.framework.dto.file.FileInfoDto;
import com.yunyao.framework.dto.reconciliation.ReconciliationApprovalDto;
import com.yunyao.framework.dto.reconciliation.ReconciliationConfirmDto;
import com.yunyao.framework.dto.reconciliation.ReconciliationMaterSaveDto;
import com.yunyao.framework.dto.reconciliation.ReconciliationMaterialDeleteDto;
import com.yunyao.framework.dto.reconciliation.ReconciliationMaterialDto;
import com.yunyao.framework.dto.reconciliation.ReconciliationSaveDto;
import com.yunyao.framework.dto.reconciliation.ReconciliationSoSupplyDeleteDto;
import com.yunyao.framework.dto.reconciliation.ReconciliationSoSupplySaveDto;
import com.yunyao.framework.dto.reconciliation.ReconciliationSubmitApprovalDto;
import com.yunyao.framework.dto.soSupply.SoSupplyMaterialDto;
import com.yunyao.framework.service.ReconciliationOrderService;
import com.yunyao.framework.service.ReconciliationService;
import com.yunyao.framework.service.SoSupplyOrderService;
import com.yunyao.framework.vo.reconciliation.ReconciliationMaterialCountVO;
import com.yunyao.framework.vo.reconciliation.ReconciliationMaterialVO;
import com.yunyao.framework.vo.reconciliation.ReconciliationOrderVO;
import com.yunyao.framework.vo.reconciliation.ReconciliationOrderinfoVO;
import com.yunyao.framework.vo.reconciliation.ReconciliationVO;
import com.yunyao.framework.vo.reconciliation.ReconciliationinfoVO;
import com.yunyao.framework.vo.sosyupply.SoSupplyMaterialVO;
import com.yunyao.web.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/reconciliation")
public class ReconciliationController {
    @Autowired
    private ReconciliationService reconciliationService;
    @Autowired
    private ReconciliationOrderService reconciliationOrderService;
    @Autowired
    private SoSupplyOrderService soSupplyOrderService;

    /**
     * 获取项目对账列表
     *
     * @param reconciliationDto
     * @return
     */
    @GetMapping("/list")
    public YResult<PageResult<ReconciliationVO>> getList(ReconciliationDto reconciliationDto) {
        return reconciliationService.pageList(reconciliationDto);
    }

    @PostMapping("/getTaxTotalPrice")
    public YResult<BigDecimal> getTaxTotalPrice(@RequestBody HistoryQtDto dto) {
        return YResult.success(reconciliationService.getTaxTotalPrice(dto));
    }

    /**
     * 获取项目对账详情信息
     *
     * @param reconciliationDto
     * @return
     */
    @GetMapping("/info")
    public YResult<ReconciliationinfoVO> getInfo(ReconciliationDto reconciliationDto) {
        return reconciliationService.getInfo(reconciliationDto);
    }

    @PostMapping("/delete")
    public YResult<Boolean> deleteInfo(@RequestBody ReconciliationSaveDto reconciliationDto) {
        return reconciliationService.deleteInfo(reconciliationDto);
    }

    @GetMapping("/order")
    public YResult<ReconciliationOrderinfoVO> getInfo(String id) {

        return reconciliationOrderService.getReconliationOrderById(id);
    }

    /**
     * 保存项目对账信息
     *
     * @param saveDto
     * @return
     */
    @PostMapping("/save")
    public YResult<String> saveInfo(@RequestBody ReconciliationSaveDto saveDto) {
        return reconciliationService.save(saveDto);
    }

    /**
     * 获取项目对账材料列表
     *
     * @return
     */
    @GetMapping("/material/list")
    public YResult<PageResult<ReconciliationMaterialVO>> getReconciliationMaterialList(ReconciliationMaterialDto reconciliationMaterialDto) {
        return reconciliationOrderService.getReconciliationMaterialList(reconciliationMaterialDto);
    }

    @GetMapping("/material/count")
    public YResult<ReconciliationMaterialCountVO> getReconciliationMaterialCount(ReconciliationDto reconciliationDto) {
        return reconciliationOrderService.getReconciliationMaterialCount(reconciliationDto);
    }

    /**
     * 获取验收材料列表
     *
     * @return
     */
    @GetMapping("/SoSupplymaterial/list")
    public YResult<PageResult<SoSupplyMaterialVO>> getContractMaterialList(SoSupplyMaterialDto soSupplyMaterialDto) {
        return soSupplyOrderService.getPoSupplyMaterialListbySupplyId(soSupplyMaterialDto);
    }

    /**
     * 保存项目对账材料信息
     *
     * @param saveDto
     * @return
     */
    @PostMapping("/material/save")
    public YResult<String> saveMaterialInfo(@RequestBody ReconciliationMaterSaveDto saveDto) {
        return reconciliationOrderService.saveMaterialInfo(saveDto);
    }

    /**
     * 删除项目对账材料信息
     *
     * @param deletedDto
     * @return
     */
    @PostMapping("/material/deleted")
    public YResult<String> deletedMaterialInfo(@RequestBody ReconciliationMaterialDeleteDto deletedDto) {
        return reconciliationOrderService.deletedMaterialInfo(deletedDto);
    }

    /**
     * 获取项目对账验收清单列表
     *
     * @return
     */
    @GetMapping("/order/list")
    public YResult<PageResult<ReconciliationOrderVO>> getReconciliationPosupplyList(ReconciliationOrderDto reconciliationOrderDto) {
        return reconciliationOrderService.getReconciliationSoSupplyList(reconciliationOrderDto);
    }

    /**
     * 保存项目对账验收清单信息
     *
     * @param saveDto
     * @return
     */
    @PostMapping("/sosupply/save")
    public YResult<String> savePoSupplyInfo(@RequestBody ReconciliationSoSupplySaveDto saveDto) {
        return reconciliationOrderService.saveSoSupplyInfo(saveDto);
    }

    /**
     * 项目对账确认
     *
     * @param reconciliationConfirmDto
     * @return
     */
    @PostMapping("/confirm")
    public YResult<String> confirm(@RequestBody @Validated ReconciliationConfirmDto reconciliationConfirmDto) {
        return reconciliationService.confirm(reconciliationConfirmDto);
    }

    @PostMapping("/check")
    public YResult<String> check(@RequestBody @Validated ReconciliationConfirmDto reconciliationConfirmDto) {
        return reconciliationService.check(reconciliationConfirmDto);
    }

    @PostMapping("/ycconfirm")
    public YResult<String> ycconfirm(@RequestBody @Validated ReconciliationConfirmDto reconciliationConfirmDto) {
        return reconciliationService.ycconfirm(reconciliationConfirmDto);
    }

    /**
     * 删除项目对账验收清单信息
     *
     * @param deletedDto
     * @return
     */
    @PostMapping("/sosupply/deleted")
    public YResult<String> deletedMaterialInfo(@RequestBody ReconciliationSoSupplyDeleteDto deletedDto) {
        return reconciliationOrderService.deletedSoSupplyInfo(deletedDto);
    }

    /**
     * 提交审批销售合同信息
     *
     * @return
     */
    @PostMapping("/submit/approval")
    public YResult<String> submitApproval(@RequestBody @Validated ReconciliationSubmitApprovalDto approvalDto) {
        return reconciliationService.submitApproval(approvalDto);
    }

    /**
     * 审批
     *
     * @return
     */
    @PostMapping("/approval")
    public YResult<String> approval(@RequestBody @Validated ReconciliationApprovalDto approvalDto) {
        return reconciliationService.approval(approvalDto);
    }

    /**
     * 导出文件
     *
     * @return
     */

    @GetMapping("/export/file")
    public YResult<String> exportFile(ReconciliationDto reconciliationDto, HttpServletResponse response) {
        try {
            List<ReconciliationExcelDto> contractMaterialExportDtoList = reconciliationService.export(reconciliationDto);
            try {
                // 这里URLEncoder.encode可以防止中文乱码
                String fileName = URLEncoder.encode("reconciliation", String.valueOf(StandardCharsets.UTF_8)) + ".xlsx";
//                response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
                //设置sheet名
                ExportParams params = new ExportParams();
                params.setSheetName("对账信息模版");
                //设置标题
//                params.setTitle("商品信息");
                // 这里需要设置不关闭流
                Workbook workbook = ExcelExportUtil.exportExcel(params, ReconciliationExcelDto.class, contractMaterialExportDtoList);
                //输出流
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                workbook.write(bos);
                byte[] bytes = bos.toByteArray();
                bos.close();
                try {
                    FileInfoDto fileInfoDto = AliOssUtil.upload(bytes,
                            fileName, null);
                    if (null != fileInfoDto) {
                        return YResult.success(fileInfoDto.getLink());
                    } else {
                        return YResult.error("连接文件服务器失败，请重试");
                    }
                } catch (Exception e) {
                    return YResult.error("下载失败，请重试");
                }
            } catch (IOException e) {
                System.out.println(e.getMessage());
            }
        } catch (Exception e) {
            log.error("导出对账信息失败", e);
        }
        return YResult.error("导出对账信息失败");
    }

}
